import { backgroundResources } from "../util/loadResource";
import  { Leafer,Group, Rect } from "leafer-ui";

export class Background {
  constructor(options) {
    const { camera } = options;
    this._camera = camera;
    console.log(backgroundResources);
    const { width, height, src } = backgroundResources[0];

    this._core = new Leafer();
    this.init({
      sceneWidth: camera.width,
      sceneHeight: camera.height,
      imageWidth: width,
      imageHeight: height,
      imageSrc: src,
    });
  }

  init(options) {
    const {
      sceneWidth,
      sceneHeight,
      imageWidth,
      imageHeight,
      imageSrc,
    } = options;
    const bgWidth = (imageWidth / imageHeight) * sceneHeight;
    const group = new Group({
      x: 0,
      y: 0,
      width: sceneWidth,
      height: sceneHeight,
    });
    this.breakPoint = bgWidth - 1;
    group.addMany(
      new Rect({
        x: 0,
        y: 0,
        width: bgWidth,
        height: sceneHeight,
        fill: {
          url: imageSrc,
          mode: "fit",
          type: "image",
        },
      }),
      new Rect({
        x: this.breakPoint,
        y: 0,
        width: bgWidth,
        height: sceneHeight,
        fill: {
          url: imageSrc,
          mode: "fit",
          type: "image",
        },
      })
    );
    this._core.add(group);
  }

  getCore() {
    return this._core;
  }

  run() {
    const group = this._core.children[0];
    group.set({
      x:
        this._camera.x <= this.breakPoint
          ? -this._camera.x
          : -this.breakPoint - this._camera.x,
    });
  }
}
